import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/character.dart';
import '../models/user.dart';

class UserProvider with ChangeNotifier {
  static const String _coinsKey = 'user_coins';
  static const String _unlockedCharactersKey = 'unlocked_characters';
  
  int _coins = 0;
  List<Character> _unlockedCharacters = [];
  User? _user;
  late SharedPreferences _prefs;
  
  int get coins => _coins;
  List<Character> get unlockedCharacters => _unlockedCharacters;
  User? get user => _user;
  
  UserProvider() {
    _loadData();
  }
  
  Future<void> _loadData() async {
    _prefs = await SharedPreferences.getInstance();
    _coins = _prefs.getInt(_coinsKey) ?? 10; // 默认10个金币
    final unlockedIds = _prefs.getStringList(_unlockedCharactersKey) ?? [];
    // TODO: 从 CharacterService 加载已解锁的角色
    notifyListeners();
  }
  
  Future<void> _saveCoins() async {
    await _prefs.setInt(_coinsKey, _coins);
  }
  
  Future<void> _saveUnlockedCharacters() async {
    final unlockedIds = _unlockedCharacters.map((c) => c.id).toList();
    await _prefs.setStringList(_unlockedCharactersKey, unlockedIds);
  }
  
  void setUser(User user) {
    _user = user;
    notifyListeners();
  }
  
  Future<void> addCoins(int amount) async {
    _coins += amount;
    await _saveCoins();
    notifyListeners();
  }
  
  Future<void> deductCoins(int amount) async {
    if (_coins >= amount) {
      _coins -= amount;
      await _saveCoins();
      notifyListeners();
    }
  }
  
  Future<void> unlockCharacter(Character character) async {
    if (!_unlockedCharacters.any((c) => c.id == character.id)) {
      _unlockedCharacters.add(character);
      await _saveUnlockedCharacters();
      notifyListeners();
    }
  }
  
  bool isCharacterUnlocked(String characterId) {
    return _unlockedCharacters.any((c) => c.id == characterId);
  }
} 